import { onMounted, ref } from 'vue';
import Login from '@/api/login/index';
import { getStorage, saveStorage } from '@/utils/uni-storage';
import { unknownType } from '@/utils/types';
import menuAPI from '@/api/menu-list';
import cloud from '../../assets/images/login_cloud.png';
import order from '../../assets/images/login_order.png';
import sale from '../../assets/images/login_sale.png';
import analysis from '../../assets/images/login_analysis.png';

interface loginForm {
    account: string;
    password: string;
    companyId: string;
    baseUrl: string;
}

export default function useLogin() {
    /**
     * 图片列表
     */
    const imageList = ref({
        cloud: cloud,
        order: order,
        sale: sale,
        analysis: analysis,
    });

    /**
     * 表单
     */
    const formRef = ref();

    const form = ref<loginForm>({
        account: '',
        password: '',
        companyId: '',
        baseUrl: getStorage('baseUrl') || import.meta.env.VITE_API_URL,
    });

    const rules = ref({
        account: {
            rules: [
                {
                    required: true,
                    errorMessage: '用户名不能为空',
                },
            ],
        },
        password: {
            rules: [
                {
                    required: true,
                    errorMessage: '密码不能为空',
                },
            ],
        },
        companyId: {
            rules: [
                {
                    required: true,
                    errorMessage: '公司不能为空',
                },
            ],
        },
    });

    /**
     * 改变 baseUrl
     */
    function handleBlur(e: any) {
        if (!e.detail.value) {
            return;
        }

        saveStorage('baseUrl', e.detail.value);
    }

    /**
     * 登录
     */
    const login = async () => {
        const validForm = ref<boolean>(false);
        await formRef.value.validate((valid: boolean) => {
            if (!valid) {
                validForm.value = true;
            } else {
                validForm.value = false;
            }
        });

        if (!validForm.value) {
            return;
        }

        // const res: unknownType = await Login.login(form.value);
        // 这里拦截登录接口
        // if (!res) {
        //     return;
        // }

        // saveStorage('token', res.data?.token);
        // saveStorage('userInfo', res.data);
        // saveStorage('BrandAndLanguage', {
        //     brand: Brand.Zebra,
        //     printLanguage: PrinterLanguage.ZPL,
        // });

        // 跳转
        uni.switchTab({ url: '/pages/home/index' });
    };

    /**
     * 页面渲染
     */
    onMounted(() => {});

    return {
        form,
        formRef,
        rules,
        imageList,
        handleBlur,
        login,
    };
}
